# +----------------------------------------------------------------------
# | ChatWork智能聊天办公系统
# +----------------------------------------------------------------------
# | 软件声明: 本系统并非自由软件,未经授权任何形式的商业使用均属非法。
# | 版权保护: 任何企业和个人不允许对程序代码以任何形式任何目的复制/分发。
# | 授权要求: 如有商业使用需求,请务必先与版权所有者取得联系并获得正式授权。
# +----------------------------------------------------------------------
# | Author: ChatWork Team <2474369941@qq.com>
# +----------------------------------------------------------------------
import json
import time
from typing import List
from exception import AppException
from common.utils.urls import UrlUtil
from common.utils.times import TimeUtil
from common.utils.config import ConfigUtil
from common.models.users import UserModel
from common.models.docs import DocsFilesModel
from common.models.docs import DocsRecordsModel
from apps.api.schemas.apply.docs import record_schema as schema


class DocsRecordService:

    @classmethod
    async def lists(cls, scene: str, code: str, user_id: int):
        """
        文件对话记录

        Args:
            scene (string): 来源场景
            code (string): 文件编号
            user_id (int): 用户ID

        Returns:
           List[any]: 对话记录列表

        Author:
           zero
        """
        files = await DocsFilesModel.filter(code=code, user_id=user_id).first()
        if files is None:
            raise AppException("文件不存在")
        if files.is_delete:
            raise AppException("文件已被删除")

        # 查询记录
        records = await (DocsRecordsModel
                         .filter(scene=scene)
                         .filter(file_id=files.id)
                         .filter(user_id=user_id)
                         .filter(is_clear=0)
                         .filter(is_delete=0)
                         .order_by("-id")
                         .limit(200)
                         .all())

        # 查询用户
        user = await UserModel.filter(id=user_id).first().values("avatar")

        # 查询头像
        chat_avatar = await ConfigUtil.get("docs", "chat_avatar", "")
        chat_avatar = await UrlUtil.to_absolute_url(chat_avatar)

        # 处理数据
        lists = []
        records = list(reversed(records))
        for item in records:
            quotes = json.loads(item.quotes or "[]")

            # 问题
            lists.append(schema.DocsRecordListVo.Question(
                id=item.id,
                type="question",
                avatar=await UrlUtil.to_absolute_url(user.get("avatar", "")),
                content=item.question,
                create_time=TimeUtil.timestamp_to_date(item.create_time)
            ))

            # 答复
            lists.append(schema.DocsRecordListVo.Answer(
                id=item.id,
                type="answer",
                avatar=chat_avatar,
                content=item.answer or "",
                thinks=item.thinks or "",
                quotes=quotes,
                end_clear=bool(item.end_clear),
                is_clear=bool(item.is_clear),
                task_time=item.task_time + "s",
                create_time=TimeUtil.timestamp_to_date(item.create_time)
            ))

        return lists

    @classmethod
    async def clear(cls, scene: str, code: str, user_id: int):
        """
        对话记录清空

        Args:
            scene (string): 来源场景
            code (string): 文件编号
            user_id (int): 用户ID

        Author:
           zero
        """
        files = await DocsFilesModel.filter(code=code, user_id=user_id).first()
        if files is None:
            raise AppException("文件不存在")
        if files.is_delete:
            raise AppException("文件已被删除")

        # 清空上下文
        await (DocsRecordsModel
               .filter(scene=scene)
               .filter(file_id=files.id)
               .filter(user_id=user_id)
               .update(
                    is_clear=1,
                    update_time=int(time.time())
                ))

        # 标记清空节点
        await (DocsRecordsModel
               .filter(scene=scene)
               .filter(file_id=files.id)
               .filter(user_id=user_id)
               .filter(is_clear=1)
               .order_by("-id")
               .limit(1)
               .update(end_clear=1))

    @classmethod
    async def delete(cls, code: str, rid: str, user_id: int):
        """
        对话记录删除

        Args:
            code (string): 文件编号
            rid (string): 记录编号
            user_id (int): 用户ID

        Author:
           zero
        """
        files = await DocsFilesModel.filter(code=code, user_id=user_id).first()
        if files is None:
            raise AppException("文件不存在")
        if files.is_delete:
            raise AppException("文件已被删除")

        record = await DocsRecordsModel.filter(file_id=files.id, code=rid, user_id=user_id).first()
        if record is None or record.is_delete:
            raise AppException("记录数据不存在")
        if record.is_clear:
            raise AppException("记录数据已被删")

        await DocsRecordsModel.filter(id=record.id).update(
            is_delete=1,
            delete_time=int(time.time())
        )
